import onewire, ds18x20, time
from lib.config.index import sensor_config
from utils import device
from machine import Pin
from lib.net import wifi


def demo():
    # vcc_pin = Pin(15, Pin.OUT)
    # vcc_pin.value(1)
    ds18b20_config = sensor_config.get_sensor("ds18b20")

    if not ds18b20_config:
        return

    # print(ds18b20_config)

    pin_num = ds18b20_config["pin"]
    ds_pin = Pin(pin_num)
    ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

    roms = ds_sensor.scan()
    print("Found DS devices: ", roms)

    wifi.do_connect_wifi()

    while True:
        ds_sensor.convert_temp()
        time.sleep_ms(750)
        for rom in roms:
            print(rom)
            tempC = ds_sensor.read_temp(rom)
            tempF = tempC * (9 / 5) + 32
            print("temperature (ºC):", "{:.2f}".format(tempC))
            print("temperature (ºF):", "{:.2f}".format(tempF))
            print()
            format_t = "{:.2f}".format(tempC)
            format_f = "{:.2f}".format(tempF)
        time.sleep(5)
        payload = {
            "op": "upload",
            "name": "dataset",
            "topic": "Tiot_ye3nnvgc",
            "device_id": device.get_device_id(),
            "data": {"temperature_C": format_t, "temperature_F": format_f},
        }
        wifi.POST(payload, "www.hanxiaoxin.cn", "/iot/upload", 8081, 4000)


def init_ds18b20(pin_num):
    ds_pin = Pin(pin_num)
    ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
    roms = ds_sensor.scan()
    print("Found DS devices: ", roms)


if __name__ == "__main__":
    demo()
